package com.example.shopping_boot.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.shopping_boot.mapper.SysPermissionMapper;
import com.example.shopping_boot.pojo.entity.SysPermissionDO;
import com.example.shopping_boot.pojo.entity.SysRoleDO;
import com.example.shopping_boot.service.ISysPermissionRoleService;
import com.example.shopping_boot.service.ISysPermissionService;
import com.example.shopping_boot.service.ISysRoleService;
import com.example.shopping_boot.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 翟羽佳
 * @since 2022-10-25
 */
@Service
@RequiredArgsConstructor
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermissionDO> implements ISysPermissionService {

    private final ISysRoleService isysRoleService;

    private final ISysPermissionRoleService iSysPermissionRoleService;

    private final RedisUtil redisUtil;

    /**
     * tool 更改权限的时候调用清空缓存方法  暂未开发
     * @param o
     * @param s
     * @return
     */
    @Override
    public List<SysPermissionDO> getPermissionList(Object o, String s) {

        Object permissionListRedis = redisUtil.getMapObject("PermissionList", o);

        if (permissionListRedis!=null) {
            return (List<SysPermissionDO>) permissionListRedis;
        }


        List<SysRoleDO> roleListByUserId = isysRoleService.getRoleListByUserId(o, s);
        List<SysPermissionDO> sysPermissions = new ArrayList<>();
        for (SysRoleDO sysRole : roleListByUserId) {
            List<SysPermissionDO> permissionByRoleId = iSysPermissionRoleService.getPermissionByRoleId(sysRole.getId());
            if (permissionByRoleId!=null) {
                sysPermissions.addAll(permissionByRoleId);
            }
        }

        redisUtil.add("PermissionList", MapUtil.of(o,sysPermissions.stream().distinct().collect(Collectors.toList())));

        return (List<SysPermissionDO>)redisUtil.getMapObject("PermissionList", o);
    }
}
